package com.lhb.boyixue.user.utils;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.lhb.boyixue.user.model.ChatMessage;
import com.lhb.boyixue.user.model.ChatRequestBody;

import java.io.*;
import java.net.*;

import java.util.LinkedList;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Consumer;

import static java.lang.System.out;

public class SparkStreamUtil {

    private static String APIPassword = "HVcwQlvoYMFPOvyPrPka:AWVphBjQyPVRNcOfkTfH";
    // 修复后 - 线程安全
    private static final ConcurrentHashMap<String, LinkedList<String>> digest = new ConcurrentHashMap<>();

    public static void streamChat(ChatRequestBody chatRequestBody, Consumer<String> onChunk) {

        String sessionId = chatRequestBody.getSessionId();
         String s=null;//上文
        String question = chatRequestBody.getQuestion();
        if(digest.containsKey(sessionId)){
            LinkedList<String> chatMessages = digest.get(sessionId);
            if(chatMessages!=null&&!chatMessages.isEmpty()){
                StringBuilder conversationText = new StringBuilder();
                int length= chatMessages.size();
                for(int i=length-1;i>=0&&i>=length-5;i--)
                {
                    String msg = chatMessages.get(i);
                    conversationText.append(msg).append("\n");
                }

                s=conversationText.toString();
            }
        }
        String prompt;
        if(s!=null&&!s.isEmpty())
            prompt= "上文:"+s + "，请联系上文帮我解答这个问题：" + question;
        else
            prompt=  "请帮我解答这个问题：" + question;
        try {
            String url = "https://spark-api-open.xf-yun.com/v1/chat/completions";

            // 创建最外层的JSON对象
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("user", sessionId);
            jsonObject.put("model", "lite");
            // 创建messages数组
            JSONArray messagesArray = new JSONArray();
            // 创建单个消息的JSON对象
            JSONObject messageObject = new JSONObject();
            System.err.println(prompt);
            messageObject.put("role", "user");
            messageObject.put("content", prompt);
            messageObject.put("temperature", "0.5");
            // 将单个消息对象添加到messages数组中
            messagesArray.put(messageObject);
            // 将messages数组添加到最外层的JSON对象中
            jsonObject.put("messages", messagesArray);
            // 设置stream属性为true
            jsonObject.put("stream", true);
            jsonObject.put("max_tokens", 4096);
            System.err.println(jsonObject);

            String header = "Authorization: Bearer" + APIPassword; // 注意此处替换自己的key和secret

            URL obj = new URL(url);
            HttpURLConnection con = (HttpURLConnection) obj.openConnection();
            con.setRequestMethod("POST");
            con.setRequestProperty("Content-Type", "application/json");
            con.setRequestProperty("Authorization", header);
            con.setDoOutput(true);

            OutputStream os = con.getOutputStream();
            os.write(jsonObject.toString().getBytes());
            os.flush();
            os.close();

            int responseCode = con.getResponseCode();
            out.println("Response Code : " + responseCode);

            BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
            String line;
            StringBuilder response = new StringBuilder();
            while ((line = in.readLine()) != null) {

                // 解析并提取content字段
                String content = extractContent(line);
                if (content != null && !content.isEmpty()) {
                    onChunk.accept(content);
                    response.append(content);
                }
            }
            System.err.println(sessionId + " 的文章生成任务内容如下：\n" + response);
            String summary = summary(new ChatMessage(question, response.toString()));




            if(digest.containsKey(sessionId))
            {
                LinkedList<String> link = digest.get(sessionId);
                link.addLast(summary);
                if (link.size()>15)
                    link.removeFirst();
                digest.put(sessionId,link);

            }else{
                LinkedList<String> link=new LinkedList<>();
                link.addLast(summary);
                digest.put(sessionId,link);
            }
            in.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static String summary(ChatMessage chatMessage) {

        StringBuilder conversationText = new StringBuilder();

            conversationText.append("用户").append(": ").append(chatMessage.getQuestion()).append("\n");
            conversationText.append("AI").append(": ").append(chatMessage.getAnswer()).append("\n");


        String prompt = "请对以下对话进行简洁摘要，保留关键信息和上下文：\n\n" +
                conversationText.toString();

        try {
            String url = "https://spark-api-open.xf-yun.com/v1/chat/completions";

            // 创建最外层的JSON对象
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("user", "1231231");
            jsonObject.put("model", "lite");
            // 创建messages数组
            JSONArray messagesArray = new JSONArray();
            // 创建单个消息的JSON对象
            JSONObject messageObject = new JSONObject();
            System.err.println(prompt);
            messageObject.put("role", "user");
            messageObject.put("content", prompt);
            messageObject.put("temperature", "0.5");
            // 将单个消息对象添加到messages数组中
            messagesArray.put(messageObject);
            // 将messages数组添加到最外层的JSON对象中
            jsonObject.put("messages", messagesArray);
            // 设置stream属性为true
            jsonObject.put("stream", true);
            jsonObject.put("max_tokens", 4096);
            System.err.println(jsonObject);

            String header = "Authorization: Bearer" + APIPassword; // 注意此处替换自己的key和secret

            URL obj = new URL(url);
            HttpURLConnection con = (HttpURLConnection) obj.openConnection();
            con.setRequestMethod("POST");
            con.setRequestProperty("Content-Type", "application/json");
            con.setRequestProperty("Authorization", header);
            con.setDoOutput(true);

            OutputStream os = con.getOutputStream();
            os.write(jsonObject.toString().getBytes());
            os.flush();
            os.close();

            int responseCode = con.getResponseCode();
            out.println("Response Code : " + responseCode);

            BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
            String line;
            StringBuilder response = new StringBuilder();
            while ((line = in.readLine()) != null) {


                // 解析并提取content字段
                String content = extractContent(line);
                if (content != null && !content.isEmpty()) {
                    response.append(content);
                }
            }
            System.err.println(" 摘要生成如下：\n" + response);
            in.close();
            return response.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
       return null;
    }

    /**
     * 从流式响应中提取content字段
     * @param line 单行响应数据
     * @return content内容，如果解析失败返回null
     */
    private static String extractContent(String line) {
        try {
            // 检查是否是结束标记
            if (line.contains("data:[DONE]")) {
                return "[[END]]"; // 返回结束标记
            }

            // 检查是否以"data:"开头
            if (line.startsWith("data:")) {
                // 去掉"data:"前缀
                String jsonStr = line.substring(5).trim();

                // 解析JSON
                JSONObject jsonObject = JSONUtil.parseObj(jsonStr);

                // 检查是否有choices数组
                if (jsonObject.containsKey("choices")) {
                    JSONArray choices = jsonObject.getJSONArray("choices");
                    if (choices.size() > 0) {
                        JSONObject choice = choices.getJSONObject(0);
                        if (choice.containsKey("delta")) {
                            JSONObject delta = choice.getJSONObject("delta");
                            if (delta.containsKey("content")) {
                                return delta.getStr("content");
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            System.err.println("解析JSON完成: " + line);

        }
        return null;
    }
}